package net.tribal.comic.services

import org.codehaus.groovy.grails.commons.ConfigurationHolder as CH
import net.tribal.comic.entities.User


class UserService {

    boolean transactional = true
    def fileService
	
	
	/**
	 * 
	 * @param instance
	 * @param file
	 * @param newPassword
	 * @param newRepeatPassword
	 * @return
	 */
    def add( instance, file, newPassword, newRepeatPassword ){
		
		this.validatePassword( instance, newPassword, newRepeatPassword )

    	if ( !instance.hasErrors() ) {
    		//	Afegim el nou fitxer
			this.changeFile( instance, file )
		}
    	
    	if ( !instance.hasErrors() ) {
    		instance.save()
    	}
    	return instance
    }
    
	
	/**
	 * 
	 * @param instance
	 * @return
	 */
    def delete( instance ) {
		try {
			def nameList = instance.nameFile.tokenize(".")
			if( !(fileService.removeFile( "/user/", instance.nameFile ) && fileService.removeFile( "/user/", nameList[0] + "_thumbnail." + nameList[1])) ) {
				instance.errors.rejectValue('',null,'no se ha podido borrar el fichero')
				log.debug "No se ha podido borrar la imagen con el nombre: ${instance.nameFile} y parametros: ${instance.toString()}"
				return instance
			}
			
			instance.delete()				
			return instance
		}
        catch (org.springframework.dao.DataIntegrityViolationException e) {
        	instance.errors.rejectValue('',null,'no se ha podido borrar el fichero por motivos de integridad de datos')
			log.debug "No se ha podido borrar la imagen con el nombre: ${instance.nameFile} y parametros: ${instance.toString()}"
        	return instance
        }
    }
    
    
    /**
     * 
     * @param instance
     * @return
     */
    def changeProfile( instance ) {

    	if (instance.version) {
            def version = instance.version.toLong()
            if (instance.version > version) {
				instance.errors.rejectValue("version", "user.optimistic.locking.failure", "Another user has updated this User while you were editing")
                return instance
            }
        }
    	
    	if ( !instance.hasErrors() ) { instance.save() }
    	
    	return instance
    }
	
	
	/**
	 * 
	 * @param instance
	 * @param file
	 * @return
	 */
    def changeFile( instance, file ) {
    	
    	//	Si existeix un fitxer amb aquest nom el borrem
		if( instance.id && file != null && !file.isEmpty() && instance.nameFile != null ) {
			def nameList = instance.nameFile.tokenize(".")
        	if( !(fileService.removeFile( "/user/", instance.nameFile ) && fileService.removeFile( "/user/", nameList[0] + "_thumbnail." + nameList[1])) ) { 
        		instance.errors.rejectValue('pathFile', delete.error, null, "NO SE HA PODIDO ELIMINAR EL FICHERO")
        		return instance
			}
    	}
		
    	if ( file != null && !file.isEmpty() ) {
			
			def validate = fileService.validate(file, CH.config.comics.maxSizeAvatar)
    		if(validate.ext != null) {
    			def randomName = fileService.addFile(file, "/user/", validate.ext)
    			
    			if (randomName == null) {		//	No ha podido guardar el fichero
    				instance.errors.rejectValue('pathFile', 'file.not.save')
    			}
    			
    			instance.nameFile = randomName + "." + validate.ext
			
    		} else {
    			instance.errors.rejectValue('pathFile', validate.error, null, "ERROR VALIDACION")
    		}
		} else {
			instance.nameFile = null 
		}
		
		return instance
    }
	
	
	/**
	 * 
	 * @param instance
	 * @param newPassword
	 * @param newRepeatPassword
	 * @return
	 */
    def changePassword ( instance, newPassword, newRepeatPassword ) {
    	def ins = this.validatePassword ( instance, newPassword, newRepeatPassword )
    			
    	if ( !ins.hasErrors() ) { ins.save() }
    	
    	return ins
    }
	
	
    /**
     * 
     * @param instance
     * @param newPassword
     * @param newRepeatPassword
     * @return
     */
    def validatePassword ( instance, newPassword, newRepeatPassword ) {
    	
    	if ( newPassword != newRepeatPassword ) {
    		instance.errors.rejectValue("password", "password.deny", null, "INTRODUZCA LOS PASSWORDS IGUALES")
    	}
		
    	return instance	
    }
}